/*
 * 语言信息模块
 * @Author: ljb
 * @Date: 2018-04-11 18:02:05
 * @Last Modified by: ljb
 * @Last Modified time: 2018-09-12 11:24:51
 */
import axios from 'axios';
import qs from 'qs';
import API_LIST from 'src/API_LIST';
import Toast from 'cube-ui/lib/toast';

// import Vue from 'vue';

const url_lang = qs.parse(window.location.search.substr(1));

const current_lang = url_lang.lang || sessionStorage.getItem('current_lang');

export default {
	namespaced: true,
	state: {

		current_lang: current_lang || 'zh-CN',

	},
	mutations: {
		/* eslint-disable no-param-reassign */
		setLang(state, lang) {
			state.current_lang = lang;
			sessionStorage.setItem('current_lang', lang);
		},
	},
	actions: {

		changeWechatUserLang({ commit }, { lang, id }) {
			const param = {

				type: 'wechat',

				id,

				language: lang,

			};

			return axios.post(API_LIST.CHANGE_LANG, param)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					commit('setLang', lang);
				})
				.catch((err) => {
					const toast = Toast.$create({
						type: 'error',
						time: 2000,
						txt: err.message || err.statusText,
					});
					toast.show();
				});
		},

	},
	getters: {
		getLang: state => state.current_lang,

	},
};
